package com.fjnu.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class DemoAspect {

    /**
     * 匹配所有DAO方法
     */
    @Pointcut("execution(public * com.fjnu.dao..*.*(..))")
    public void daoLayer() {
    }

    /**
     * 专门匹配所有delete开头的方法
     */
    @Pointcut("execution(public * com.fjnu.dao.*.delete*(..))")
    public void deleteMethods() {
    }

    /**
     * 方法执行前通知
     */
    @Before("daoLayer()")
    public void beforeExecutionAdvice(JoinPoint jpoint) {
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("[INFO] [" + currentTime + "] " + jpoint.getSignature().getName() + " method start execution.");
    }

    /**
     * 方法执行后通知
     */
    @After("daoLayer()")
    public void afterExecutionAdvice(JoinPoint jpoint) {
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("[INFO] [" + currentTime + "] " + jpoint.getSignature().getName() + " method execution completed.");
    }

    /**
     * delete方法特殊通知
     */
    @Before("deleteMethods()")
    public void beforeDeleteExecutionAdvice(JoinPoint jpoint) {
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("[WARN] [" + currentTime + "] Delete operation detected - " + jpoint.getSignature().getName() + " method start execution.");
    }

    /**
     * 方法执行时间监控
     */
    @Around("daoLayer()")
    public Object performanceLogAdvice(ProceedingJoinPoint pjointpoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object ret = pjointpoint.proceed();
        long endTime = System.currentTimeMillis();

        // 转换为秒，保留1位小数
        double seconds = (endTime - startTime) / 1000.0;
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        System.out.println("[INFO] [" + currentTime + "] " + pjointpoint.getSignature().getName() + " method was executed and spent " + String.format("%.1f", seconds) + " second.");
        return ret;
    }
}